<template>
  <div v-if="userInfo">
    <el-avatar
      v-if="userInfo.avatar"
      :size="40"
      :src="userInfo.avatar.replace(/public/, baseURL)"
      @click="startUpload"
    ></el-avatar>
    <el-avatar
      v-else
      :size="40"
      :src="circleUrl"
      @click="startUpload"
    ></el-avatar>
    <input
      type="file"
      name="file"
      class="inputfile"
      ref="file"
      @change="chooseFile"
    />
  </div>
</template>

<script>
import { reactive, toRefs, computed, ref } from "vue";
import { useStore } from "vuex";
import { ajax } from "@/api";
// 上传头像  == 上传文件
export default {
  setup() {
    const store = useStore();
    const file = ref();
    const userInfo = computed(() => store.state.userInfo); // 不能展开解构
    const state = reactive({
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    });

    const chooseFile = async () => {
      console.log("chooseFile");
      var filedata = file.value.files[0]; // 需要上传的文件
      // 表单提交
      var data = new FormData(); // 新建表单模型对象 提交数据
      data.append("file", filedata);
      console.log(filedata);

      // 上传文件
      let { result, code, path } = await ajax.uploadfile(data);

      if (code == 200) {
        // 修改用户信息
        ajax
          .changeinfo({
            avatar: path,
          })
          .then((res) => {
            if (res.code == 200) {
              var info = store.state.userInfo;
              store.commit("changeUserInfomu", {
                ...info,
                avatar: path,
              });
            }
          });
      }
    };

    const startUpload = () => {
      file.value.click();
    };
    return {
      ...toRefs(state),
      userInfo,
      chooseFile,
      startUpload,
      file,
    };
  },
};
</script>


<style lang="scss" scoped>
.inputfile {
  display: none;
}
</style>